<script setup>
import { reactive, ref, toRaw, watch } from 'vue'
import { queryFirstTwoLevelsOfCategories, addCategory } from '@/service/category.js'
import { ElNotification, ElTreeSelect } from 'element-plus'
import PlusIcon from '@/components/icons/PlusIcon.vue'
import { upload } from '@/service/file.js'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
  },
})
const categoryList = ref([])
const showDialog = ref(false)
const levelMap = {}
watch(
  () => props.visible,
  async (val) => {
    showDialog.value = val
    if (val) {
      const res = await queryFirstTwoLevelsOfCategories()
      let arr = []
      res.data.forEach((item) => {
        const category = {}
        category.value = item.id
        category.label = item.name
        levelMap[item.id] = item.level
        if (!item.hasChildren) {
          arr.push(category)
        } else {
          const children = []
          item.children.forEach((child) => {
            const subCategory = {}
            subCategory.value = child.id
            subCategory.label = child.name
            levelMap[child.id] = child.level
            children.push(subCategory)
          })
          category.children = children
          arr.push(category)
        }
      })
      arr.unshift({
        value: -1,
        label: '顶级分类',
      })
      categoryList.value = arr
    } else {
      Object.assign(form, {
        name: null,
        parentId: -1,
        level: 1,
        icon: null,
        status: 1,
        sort: 0,
      })
    }
  }
)
let form = reactive({
  name: null,
  parentId: -1,
  level: 1,
  icon: null,
  status: 1,
  sort: 0,
})
const emits = defineEmits(['closeDialog', 'finishSaveAction'])

const fileInput = ref()

function openFileSelector() {
  fileInput.value.click()
}

async function handleFileSelect(event) {
  const selectedFile = event.target.files[0]
  const res = await upload(selectedFile)
  form.icon = res.data
}

watch(
  () => form.parentId,
  (newValue) => {
    form.level = levelMap[newValue] + 1
  }
)
const rules = reactive({
  name: [{ required: true, message: '分类名称不可为空！', trigger: 'blur' }],
  icon: [
    {
      required: () => form.level === 3, // 仅三级分类时必填
      message: '三级分类必须上传图片！',
      trigger: 'blur',
    },
  ],
})
const dialog = ref()

function onTapSaveCategoryButton() {
  dialog.value.validate(async (valid) => {
    if (valid) {
      await addCategory(toRaw(form))
      ElNotification({
        title: '提示',
        message: '添加成功！',
        type: 'success',
      })
      emits('finishSaveAction')
    }
  })
}
</script>

<template>
  <el-dialog width="500px" draggable v-model="showDialog" title="新增商品分类" @close="emits('closeDialog')">
    <el-form ref="dialog" :model="form" label-position="right" label-width="auto" :rules="rules">
      <el-form-item label="分类名称:" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="上级分类:">
        <el-tree-select
          check-strictly
          v-model="form.parentId"
          :data="categoryList"
          :render-after-expand="false"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item v-if="form.level === 3" label="分类图片:" prop="icon">
        <div class="form-image" @click="openFileSelector">
          <img v-if="form.icon" :src="form.icon" alt="" style="width: 100%; height: 100%" />
          <el-icon v-else size="35">
            <PlusIcon />
          </el-icon>
          <input
            type="file"
            ref="fileInput"
            class="hidden-file-input"
            @change="handleFileSelect"
            accept="image/*"
            style="display: none"
          />
        </div>
      </el-form-item>
      <el-form-item label="状态:">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序:">
        <el-input-number v-model="form.sort" :min="1" :max="100" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emits('closeDialog')">取消</el-button>
        <el-button type="primary" @click="onTapSaveCategoryButton">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.form-image {
  width: 100px;
  height: 100px;
  border: 1px dashed gray;
  color: gray;
  display: flex;
  justify-content: center;
  align-items: center;

  &:hover {
    border: 1px dashed #409eff;
    color: #409eff;
    cursor: pointer;
  }
}
</style>
